/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.adapter.io;

import java.io.*;
import java.nio.channels.FileChannel;

/**
 * @author Gregor Schauer
 */
public class SerializableFileReader extends FileReader implements SerializableFileInput {
	protected File file;
	protected RandomAccessFile randomAccessFile;
	protected FileDescriptor fD;

	public SerializableFileReader(String name) throws IOException {
		this(new File(name));
	}

	public SerializableFileReader(File file) throws IOException {
		this(new RandomAccessFile(file, "r"), file);
	}

	public SerializableFileReader(FileDescriptor fileDescriptor, File file) {
		super(fileDescriptor);
		this.file = file;
	}

	public SerializableFileReader(RandomAccessFile randomAccessFile, File file) throws IOException {
		super(randomAccessFile.getFD());
		this.randomAccessFile = randomAccessFile;
		this.file = file;
		this.fD = this.randomAccessFile.getFD();
	}

	@Override
	public File getFile() {
		return file;
	}

	@Override
	public FileDescriptor getFD() {
		return fD;
	}

	@Override
	public FileChannel getChannel() {
		return randomAccessFile.getChannel();
	}

	@Override
	public long getBytesRead() throws IOException {
		return getChannel().position();
	}

	@Override
	public long skip(long n) throws IOException {
		if (randomAccessFile != null) {
			randomAccessFile.seek(n);
		} else {
			return super.skip(n);
		}
		return n;
	}

	@Override
	public void close() throws IOException {
		try {
			randomAccessFile.close();
		} finally {
			super.close();
		}
	}
}
